import { defineStore } from 'pinia'
import { ref } from 'vue'
import { ToolType } from '@/types/tools.ts'

// 主题管理 store
export const useThemeStore = defineStore('theme', () => {
  const isDark = ref(false)

  // 初始化主题（从 localStorage 读取或根据系统偏好设置）
  function initTheme() {
    const savedTheme = localStorage.getItem('theme')
    if (savedTheme) {
      isDark.value = savedTheme === 'dark'
    } else {
      // 根据系统偏好设置
      isDark.value = window.matchMedia('(prefers-color-scheme: dark)').matches
    }
    applyTheme()
  }

  // 应用主题
  function applyTheme() {
    if (isDark.value) {
      document.documentElement.classList.add('dark')
    } else {
      document.documentElement.classList.remove('dark')
    }
    localStorage.setItem('theme', isDark.value ? 'dark' : 'light')
  }

  // 切换主题
  function toggleTheme() {
    isDark.value = !isDark.value
    applyTheme()
  }

  // 设置主题
  function setTheme(dark: boolean) {
    isDark.value = dark
    applyTheme()
  }

  return { isDark, initTheme, toggleTheme, setTheme }
})

// 应用管理 store
// export const useAppStore = defineStore('app', () => {
//     const appList = ref<ToolType[]>([])
// })

// 任务管理 store
export const useTaskStore = defineStore('task', () => {
  const taskList = ref<ToolType[]>([])

  function addTask(task: ToolType) {
    if (!taskList.value.some((t) => t.name === task.name)) {
      taskList.value.push(task)
    }
  }

  function removeTask(task: ToolType) {
    const idx = taskList.value.findIndex((t) => t.name === task.name)
    if (idx > -1) taskList.value.splice(idx, 1)
  }
  return { taskList, addTask, removeTask }
})
